package com.music.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.music.dao.AdminMapper;
import com.music.dao.UserMapper;
import com.music.entity.Admin;
import com.music.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @className: AdminServiceImpl
 * @description:
 * @author: 林鑫海
 * @date: 2022/7/5
 **/
@Service
@Transactional
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private HttpServletRequest request;

    @Override
    public boolean existOfPhoneNumber(String adminPhone) {
        Admin admin = new Admin();
        admin.setAdminPhone(adminPhone);
        List<Admin> adminPhoneList = adminMapper.findSelective(admin);
        return !adminPhoneList.isEmpty();
    }

    @Override
    public Admin login(String adminPhone, String adminPassword) {
        Admin admin = new Admin();
        admin.setAdminPhone(adminPhone);
        admin.setAdminPassword(adminPassword);
        List<Admin> list = adminMapper.findSelective(admin);
        if (!list.isEmpty()){
            //获取管理员信息
            Admin admin1 = list.get(0);
            //登录成功，存入session中
            request.getSession().setAttribute("admin",admin1);
            return admin1;
        }
        return null;
    }

    @Override
    public void logout() {
        request.getSession().removeAttribute("admin");
    }

    @Override
    public Admin getAdminBySession() {
        return (Admin) request.getSession().getAttribute("admin");
    }

    @Override
    public PageInfo<Admin> getAdminByPage(int pageNum, int pageSize, Admin admin) {
        StringBuffer adminPhone = new StringBuffer();
        // 判断参数情况，拼接字符串匹配符%
        if (admin.getAdminPhone() != null && !"".equals(admin.getAdminPhone())) {
            // 进行管理员账号关键字查询
            adminPhone.append("%").append(admin.getAdminPhone()).append("%");// where A.admin_id like '%管理员账号%';
            // 重新设值
            admin.setAdminPhone(adminPhone.toString());
        }
        //开始分页
        PageHelper.startPage(pageNum,pageSize);
        //执行select查询语句
        List<Admin> adminList = adminMapper.findPageSelective(admin);
        //封装分页对象
        PageInfo<Admin> pageInfo = new PageInfo<>(adminList);
        return pageInfo;
    }

    @Override
    public boolean addAdmin(Admin admin) {
        //调用持久层
        return adminMapper.byInsert(admin)>0;
    }

    @Override
    public boolean modifyAdmin(Admin admin) {
        //调用持久层
        return adminMapper.byUpdate(admin)>0;
    }

    @Override
    public int deleteByAdminId(Integer adminId) {
        //调用持久层
        return adminMapper.byDelete(adminId);
    }


}
